package main

import (
	zhcn "code.google.com/p/go.text/encoding/simplifiedchinese"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
)

func decode(gbk []byte) ([]byte, error) {
	dst := make([]byte, len(gbk)*2)
	n, _, err := zhcn.GBK.NewDecoder().Transform(dst, gbk, true)
	if err != nil {
		return gbk, err
	}
	return dst[:n], err
}
func getFilelist(path1 string, topath string) {
	path1 = strings.Replace(path1, "\\", "/", -1)
	topath = strings.Replace(topath, "\\", "/", -1)
	l := len(path1)

	err := filepath.Walk(path1, func(path string, f os.FileInfo, err error) error {
		if f == nil {
			return err
		}
		if f.IsDir() {
			os.MkdirAll(topath+path[l:], os.ModePerm)
		} else {
			gbk, err := read(path)
			decoded, err := decode(gbk)
			if err != nil {
				//fmt.Printf("err decoding gbk: %s\n", err.Error())
				println("can not encoding file", path, "just copy it")
			}
			err = writ(decoded, topath+path[l:])
			if err != nil {
				println(err.Error())
			}
		}
		return err
	})
	if err != nil {
		fmt.Printf("filepath.Walk() returned %v\n", err)
	}
}
func read(from string) ([]byte, error) {
	gbk, err := ioutil.ReadFile(from)
	if err != nil {
		fmt.Printf("err reading gbk: %s\n", err.Error())
		return nil, err
	}
	return gbk, nil
}

func writ(utf []byte, to string) error {

	if err := ioutil.WriteFile(to, utf, 0666); err != nil {
		fmt.Printf("err writing decoded: %s\n", err.Error())
		return err
	}
	return nil
}
func main() {

	if len(os.Args) != 3 {
		fmt.Println("please input to args,as: \"/home/aaa/from\" \"/home/aaa/to\"")
	}
	from := os.Args[1]
	to := os.Args[2]
	println("copy from", from, "to", to, ",and transform encoding from gbk to utf-8")
	getFilelist(from, to)
}
